package com.bibrApp.difu.api;

import android.app.Activity;
import android.content.Intent;


import com.bibrApp.difu.Config;
import com.bibrApp.difu.DfApp;
import com.bibrApp.difu.actvity.login_mvp.LoginActivity;
import com.bibrApp.difu.utils.AppManager;
import com.bibrApp.difu.utils.BiBrShare;
import com.bibrApp.difu.utils.IntentUtil;
import com.bibrApp.difu.utils.ToastUtils;

import java.io.IOException;
import java.util.Objects;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;


public class TokenInterceptor implements Interceptor {


    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        //根据和服务端的约定判断token过期,过期去重新登陆
        if (isTokenExpired(response)) {
            Activity activity = AppManager.getTopActivity();
            if (activity != null) {
                ToastUtils.ShowToast(activity, "token过期,请重新登陆");
                BiBrShare.getShare(activity, Config.FILE_ACCOUNT).clearAll();
                DfApp app = (DfApp) activity.getApplication();
                app.setuId(null);
                app.setUserId(null);
                app.setToken(null);
                app.setmData(null);
                app.setNickImage(null);
                app.setNickName(null);
                app.setMemberId(null);

                IntentUtil.toActivity(LoginActivity.class, activity);

            }
        }

        return response;
    }

    /**
     * 根据Response，判断Token是否失效
     */
    private boolean isTokenExpired(Response response) {
        int code = response.code();
        return code >= 600 && code < 700;
    }
}